var writeForm;

function initWrite( oneClientData, oneProjectData, selectedSubMenuCode ) {
	boardLayout.detachObject(true);
	
	boardLayout.attachHTMLString(
			'<div id="inputDiv"><form id="writeFrom" method="POST" action="/bwf/board/insertContent" enctype="multipart/form-data"></div>');
	
	initWriteForm( oneClientData, oneProjectData, selectedSubMenuCode );
}


function initWriteForm( oneClientData, oneProjectData, selectedSubMenuCode ) {
	// file attach form index
	var fileFormIndex = 3;
	
	// file form map
	var fileAttachMap = new HashMap();
	
	var formStructure = [
	                     {type : 'settings', position : 'label-left'}
	                     ,{type : 'block', blockOffset : 0
	                    	 ,list : [
	                    	          {type : 'label', label : '작성자', labelWidth : 102}
	                    	          ,{type : 'newcolumn'}
	                    	          ,{type : 'input', name : 'writer', inputWidth : 230}
	                    	          ]
	                     }
	                     ,{type : 'block', blockOffset : 0
	                    	 ,list : [
	                    	          {type : 'label', label : '제목', labelWidth : 102}
	                    	          ,{type : 'newcolumn'}
	                    	          ,{type : 'input', name : 'title', inputWidth : 230}
	                    	          ]
	                     }
	                     ,{type : 'block', blockOffset : 0
	                    	 ,list : [
	                    	          {type : 'label', label : '파일 첨부'}
	                    	          ,{type : 'newcolumn'}
	                    	          ,{type : 'button', name : 'button_fileFormAdd', value : '+'}
	                    	          ,{type : 'newcolumn'}
	                    	          ,{type : 'file', name : 'uploadfile'}
	                    	          ,{type : 'newcolumn'}
	                    	          ,{type : 'button', name : 'button_fileClear', value : 'x'}
	                    	          ]
	                     }
	                     ,{type : 'label', label : '내용'}
	                     ,{type : 'editor', name : 'input_content', inputWidth : 640, inputHeight : 300
	                    	 ,toolbar:true
	                    	 ,iconsPath: IMAGE_PATH}
	                     ,{type : 'block', blockOffset : 0, offsetLeft : 505 
	                    	 ,list : [
	                    	          {type : 'button', name : 'button_list', value : '목록', width : 30}
	                    	          ,{type : 'newcolumn'}
	                    	          ,{type : 'button', name : 'button_write', value : '글쓰기', width : 34}
	                    	          ]}
	                     ,{type : 'hidden', name : 'content'}
	                     ];
	
	writeForm = new dhtmlXForm('writeFrom', formStructure);
	
	//Button Event
	writeForm.attachEvent('onButtonClick', function(name) {
		if ( name == 'button_fileFormAdd' ) {
			var itemData = {type : 'block', blockOffset : 0, name : 'block_AttachFileForm' + fileFormIndex
					,list : [
					         {type : 'label', label : ' ', labelWidth : 102}
					         ,{type : 'newcolumn'}
					         ,{type : 'file', name : 'uploadfile'}
					         ,{type : 'newcolumn'}
					         ,{type : 'button', name : 'button_fileFormRemove' + fileFormIndex, value : 'x'}
					         ]
			};
			
			writeForm.addItem(null, itemData, fileFormIndex);
			
			fileAttachMap.put('button_fileFormRemove' + fileFormIndex, 'block_AttachFileForm' + fileFormIndex);
			fileFormIndex++;
		}
		else if ( name == 'button_fileClear' ) {
			var value = writeForm.getItemValue('uploadfile');
			
			if ( value.length != 0 ) {
				var object 	= writeForm.getInput('uploadfile');
				$('#' + object.id).replaceWith($('#' + object.id).clone());
			}
		}
		else if ( fileAttachMap.containsKey(name) ) {
			writeForm.removeItem(fileAttachMap.get(name));
			
			fileAttachMap.remove(name);
			fileFormIndex--;
		}
		else if ( name == 'button_list' ) {
			initTable(oneClientData, oneProjectData, selectedSubMenuCode);
		}
		else if ( name == 'button_write' ) {
			dhtmlx.confirm('해당 글을 작성하시겠습니까?', function(result){
				var title  	= writeForm.getItemValue('input_title');
				var content = writeForm.getItemValue('input_content');
				
				if ( result == true ) {

					if ( title == '' ) {
						dhtmlx.alert({
							title:'title Error',
							type:'alert-error',
							text:'제목을 입력해주세요.'
						});
						return;
					}
					else if ( content == '' ) {
						dhtmlx.alert({
							title:'content Error',
							type:'alert-error',
							text:'내용을 입력해주세요.'
						});
						return;
					}
					writeForm.setItemValue('content',content);

					$('#writeFrom').submit(); 
					
					/*	 var writer = 'test';
				 var title  = writeForm.getItemValue('input_title');
				 var content = writeForm.getItemValue('input_content');
//				 var uploadfile = writeForm.getItemValue('form_file');

				 if ( title == '' ) {
					 dhtmlx.alert({
						 title:"title Error",
						 type:"alert-error",
						 text:"제목을 입력해주세요."
					 });
					 return;
				 }
				 else if ( content == '' ) {
					 dhtmlx.alert({
						 title:"content Error",
						 type:"alert-error",
						 text:"내용을 입력해주세요."
					 });
					 return;
				 }*/

					/*	 var uploadfile = new FormData();
				 uploadfile.append("form_file",$("input[name=form_file]")[0].files[0]);
					 */

					/*insertContent( oneClientData, oneProjectData, selectedSubMenuCode ,
						 writer,title,content, uploadfile);*/

				}
			});
		}
	});

/*	$('#writeFrom').ajaxForm({
	    beforeSubmit: function(){ 
	    alert('서브밋 직전입니다!'); 
	  }
	  ,success: function(data){
	      alert('fileUpload '+data);
	      initTable( oneClientData, oneProjectData, selectedSubMenuCode );
	    }

	  });*/
	
	
	$('#writeFrom').ajaxForm({
		beforeSubmit : function(formData, jqForm, options) {
			// 전송 전 처리
			// 업로드 파일이 없을 경우, 업로드 파일 data를 삭제
			var fileDataIndex  = -1;
			$.each(formData, function(i, v) {
				if( v.name == 'uploadfile' ) { // input type="file" name="upload_file" << 네임 값
					if( v.value.length == 0 ) {
						fileDataIndex  = i;
					}
				}
			});
			
			if( fileDataIndex != -1 ) {
				formData.splice(fileDataIndex, 1);
			}
		},
		success : function(responseText, statusText, xhr, $form) {
			// 완료 후 처리
//			alert('fileUpload '+data);
			initTable(oneClientData, oneProjectData, selectedSubMenuCode);
		}
	});
}



function insertContent( oneClientData, oneProjectData, selectedSubMenuCode ,writer, title, content, uploadfile) {
	$.ajax({
		url: '/bwf/board/insertContent',
		processData: false,
		contentType: false,
		data: uploadfile,
		type: 'POST',
		success: function(result){
			alert('업로드 성공!!');
		}
	});
	insertRequest.done(function(boardList) {
		initTable(oneClientData, oneProjectData, selectedSubMenuCode);
	});
	insertRequest.fail(function(jqXHR, textStatus) {
		alert('Request failed!');
	});

	
	/*var json = $.toJSON({
		'writer' 	  : writer
		,'title' 	  : title
		,'content'	  : content
//		,'uploadfile' : uploadfile
		});
	
	var insertRequest = $.ajax({
		url : '/bwf/board/insertContent'
		,type : 'POST'
		,contentType : 'application/json; charset=UTF-8'
		,data : json
		,dataType : 'json'
	});
	insertRequest.done(function(boardList) {
		initTable( oneClientData, oneProjectData, selectedSubMenuCode );
	});
	insertRequest.fail(function(jqXHR, textStatus) {
		alert('Request failed!');
	});*/
}